/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component, Fragment } from 'react';
import { Form, Input, DatePicker, message, Button, Tabs, Alert, Table,Col,Row } from 'antd';
import { connect } from 'dva';
import L from 'leaflet';   //引入leaflet
import MyPagination from '@/components/MyPagination';
import './index.less';
import './../Home/leaflet.less';
import Template2 from './Template2';
import { getTimeDistance,timeStamp } from '@/utils/utils';
import ReactDataGrid from 'react-data-grid';
import forEach from 'lodash/forEach';
import moment from 'moment';
import request from '@/utils/request';
import ReactEcharts from 'echarts-for-react';
const { TabPane } = Tabs;
const ButtonGroup = Button.Group;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showType: 1,
      historyData: [],
      config_data: {
        modbus: [{}]
      },
      start_date: moment().format('YYYY-MM-DD'),
      end_date: moment().format('YYYY-MM-DD'),
      isWatch:false,
      tabPanes: [{
        name: '设备信息',
        key: 'device',
      },{
        name: '水质监测历史',
        key: 'modbus',
      }],
      device_0: {
        meta: { total: 0, per_page: 0, current_page: 1 },
        data: [],
        loading: false,
      },
      modbus_0: {
        meta: { total: 0, per_page: 0, current_page: 1 },
        data: [],
        loading: false,
      },
      modbus_0_chart: {
        meta: { total: 0, per_page: 0, current_page: 1 },
        data: [], loading: false,
      },
    };
  }

  componentDidMount() {
    const that = this;
    this.fetchBaseInfo();
    this.fetch({
      type: 'modbus',
      channel: 0,
      page: 1,
      per_page: 20,
    });
    this.fetch({
      type: 'device',
      channel: 0,
      page: 1,
      per_page: 20,
    });
    that.fetSensors()
    this.timer=setInterval(function() {
      that.fetSensors();
      that.fetHistory();
      // that.fetchBaseInfo();
    },15000)

  }
  fetchBaseInfo=()=>{
    const that = this;
    request(`/workstations/${this.props.editRecord.id}`, {
      method: 'GET',
      params: {},
    }).then((response) => {
      if (response.status === 200) {
        console.log('response', response);
        this.setState({
          config_data: response.data.data.hardware_configs,
          // isWatch:response.data.data.is_watch
        });
      }
    });
  }
  openWatch=()=>{
    const that=this;
    request(`/workstations/${this.props.editRecord.id}/watch_mode`, {
      method: 'PUT',
    }).then(response => {
      if (response.status === 200) {
        message.success('开启监控模式成功')
        that.fetchBaseInfo()

      }
    });
  }
  componentWillUnmount() {
    if(this.timer){
      clearInterval(this.timer)
    }
  }
  fetSensors=()=>{
    this.fetchChart({
      type:'modbus',
      channel:0,
      page:1,
      per_page:50,
    })
  }

  selectDate = (type) => {
    const that = this;
    this.setState({
      rangePickerValue: getTimeDistance(type),
    }, function() {
      // that.fetch();
    });
  };
  fetch = (params) => {
    const that = this;
    this.setState({
      [`${params.type}_${params.channel}`]: {
        meta: this.state[`${params.type}_${params.channel}`].meta,
        data: this.state[`${params.type}_${params.channel}`].data,
        loading: true,
      },
    });
    request(`/workstation_historical_data`, {
      method: 'GET',
      params: {
        ...params,
        start_date: this.state.start_date,
        end_date: this.state.end_date,
        workstation_id: this.props.editRecord.id,
        order_direction:'desc'
      },
    }).then(response => {
      if (response.status === 200) {
        that.setState({
          [`${params.type}_${params.channel}`]: {
            meta: response.data.meta,
            data: response.data.data,
            loading: false,

          },
        });
      }
    });
  };
  fetchChart = (params) => {
    const that = this;
    request(`/workstation_historical_data`, {
      method: 'GET',
      params: {
        ...params,
        start_date: this.state.start_date,
        // start_date: '2020-10-10',
        end_date: this.state.end_date,
        workstation_id: this.props.editRecord.id,
        order_direction:'desc'
      },
    }).then(response => {
      if (response.status === 200) {
        that.setState({
          [`${params.type}_${params.channel}_chart`]: {
            meta: response.data.meta,
            data: response.data.data,
            loading: false,
          },
        });
      }
    });
  };
  handleRangePickerChange = (dateString, type) => {
    const that = this;
    this.setState({
      [type]: dateString,
    }, function() {

    });
  };
  fetHistory=()=>{
    this.fetch({
      type: 'device',
      channel: 0,
      page: 1,
      per_page: 20,
    });
    this.fetch({
      type: 'modbus',
      channel: 0,
      page: 1,
      per_page: 20,
    });
  }
  getOption=()=>{
    let phData=[];
    let time=[];
    let sensor_0=JSON.parse(JSON.stringify(this.state.modbus_0_chart))
    let sensor_0_reverse=sensor_0.data.reverse()
    for(let i=0;i<sensor_0_reverse.length;i++){
      if(sensor_0_reverse[i]){
        time.push(sensor_0_reverse[i].collected_at.slice(11))
        if(this.state.config_data.modbus[0].channel1_type==1){
          phData.push(sensor_0_reverse[i].data.measure_value1)
        }else if(this.state.config_data.modbus[0].channel2_type==1){
          phData.push(sensor_0_reverse[i].data.measure_value2)
        }else if(this.state.config_data.modbus[0].channel3_type==1){
          phData.push(sensor_0_reverse[i].data.measure_value3)
        }else if(this.state.config_data.modbus[0].channel4_type==1){
          phData.push(sensor_0_reverse[i].data.measure_value4)
        }else{
          phData.push('-')
        }
        // phData.push(sensor_0_reverse[i].data.pressure)
      }
    }
    var colors = ['#ff5190'];
    let option = {
      color:colors,
      title: {
        text: 'PH值',
        textStyle:{
          color:'#ff5190'
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['PH值(pH)']
      },
      grid: {
        top:'35px',
        left: '3%',
        right: '5%',
        bottom: '4%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data:time,
        axisLabel: {
          showMaxLabel: true
        }
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: 'PH值(pH)',
          type: 'line',
          large:true,
          smooth:true,
          data: phData,
          lineStyle:{
            width:5
          },
          itemStyle: {
            normal: {
              label: {
                show: true,
                position: 'top',
                textStyle: {
                  fontSize: 16,
                  color: "#fff"
                },
                formatter: (params) => {
                  if (phData.length - 1 == params.dataIndex) {
                    return params.value
                  } else {
                    return ""
                  }
                },
              },
            }
          },
        },

      ]
    };
    return option
  }
  getOption2=()=>{
    let phData=[];
    let time=[];
    let sensor_0=JSON.parse(JSON.stringify(this.state.modbus_0_chart))
    let sensor_0_reverse=sensor_0.data.reverse()
    for(let i=0;i<sensor_0_reverse.length;i++){
      if(sensor_0_reverse[i]){
        time.push(sensor_0_reverse[i].collected_at.slice(11))
        if(this.state.config_data.modbus[0].channel1_type==2){
          phData.push(sensor_0_reverse[i].data.measure_value1)
        }else if(this.state.config_data.modbus[0].channel2_type==2){
          phData.push(sensor_0_reverse[i].data.measure_value2)
        }else if(this.state.config_data.modbus[0].channel3_type==2){
          phData.push(sensor_0_reverse[i].data.measure_value3)
        }else if(this.state.config_data.modbus[0].channel4_type==2){
          phData.push(sensor_0_reverse[i].data.measure_value4)
        }else{
          phData.push('-')
        }
        // phData.push(sensor_0_reverse[i].data.pressure)
      }
    }
    var colors = ['#f36906'];
    let option = {
      color:colors,
      title: {
        text: '浊度',
        textStyle:{
          color:'#f36906'
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['浊度(NTU)']
      },
      grid: {
        top:'35px',
        left: '3%',
        right: '6%',
        bottom: '4%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data:time,
        axisLabel: {
          showMaxLabel: true
        }
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '浊度(NTU)',
          type: 'line',
          large:true,
          smooth:true,
          data: phData,
          lineStyle:{
            width:5
          },
          itemStyle: {
            normal: {
              label: {
                show: true,
                position: 'top',
                textStyle: {
                  fontSize: 16,
                  color: "#fff"
                },
                formatter: (params) => {
                  if (phData.length - 1 == params.dataIndex) {
                    return params.value
                  } else {
                    return ""
                  }
                },
              },
            }
          },
        },

      ]
    };
    return option
  }
  getOption3=()=>{
    let phData=[];
    let time=[];
    let sensor_0=JSON.parse(JSON.stringify(this.state.modbus_0_chart))
    let sensor_0_reverse=sensor_0.data.reverse()
    for(let i=0;i<sensor_0_reverse.length;i++){
      if(sensor_0_reverse[i]){
        time.push(sensor_0_reverse[i].collected_at.slice(11))
        if(this.state.config_data.modbus[0].channel1_type==3){
          phData.push(sensor_0_reverse[i].data.measure_value1)
        }else if(this.state.config_data.modbus[0].channel2_type==3){
          phData.push(sensor_0_reverse[i].data.measure_value2)
        }else if(this.state.config_data.modbus[0].channel3_type==3){
          phData.push(sensor_0_reverse[i].data.measure_value3)
        }else if(this.state.config_data.modbus[0].channel4_type==3){
          phData.push(sensor_0_reverse[i].data.measure_value4)
        }else{
          phData.push('-')
        }
        // phData.push(sensor_0_reverse[i].data.pressure)
      }
    }
    var colors = ['#127bff'];
    let option = {
      color:colors,
      title: {
        text: '溶氧',
        textStyle:{
          color:'#127bff'
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['溶氧(ppm)']
      },
      grid: {
        top:'35px',
        left: '3%',
        right: '5%',
        bottom: '4%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data:time,
        axisLabel: {
          showMaxLabel: true
        }
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '溶氧(ppm)',
          type: 'line',
          large:true,
          smooth:true,
          data: phData,
          lineStyle:{
            width:5
          },
          itemStyle: {
            normal: {
              label: {
                show: true,
                position: 'top',
                textStyle: {
                  fontSize: 16,
                  color: "#fff"
                },
                formatter: (params) => {
                  if (phData.length - 1 == params.dataIndex) {
                    return params.value
                  } else {
                    return ""
                  }
                },
              },
            }
          },
        },

      ]
    };
    return option
  }
  getOption4=()=>{
    let phData=[];
    let time=[];
    let sensor_0=JSON.parse(JSON.stringify(this.state.modbus_0_chart))
    let sensor_0_reverse=sensor_0.data.reverse()
    for(let i=0;i<sensor_0_reverse.length;i++){
      if(sensor_0_reverse[i]){
        time.push(sensor_0_reverse[i].collected_at.slice(11))
        if(this.state.config_data.modbus[0].channel1_type==4){
          phData.push(sensor_0_reverse[i].data.measure_value1)
        }else if(this.state.config_data.modbus[0].channel2_type==4){
          phData.push(sensor_0_reverse[i].data.measure_value2)
        }else if(this.state.config_data.modbus[0].channel3_type==4){
          phData.push(sensor_0_reverse[i].data.measure_value3)
        }else if(this.state.config_data.modbus[0].channel4_type==4){
          phData.push(sensor_0_reverse[i].data.measure_value4)
        }else{
          phData.push('-')
        }
        // phData.push(sensor_0_reverse[i].data.pressure)
      }
    }
    var colors = ['#00cf79'];
    let option = {
      color:colors,
      title: {
        text: '电导率',
        textStyle:{
          color:'#00cf79'
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['电导率(μS/CM)']
      },
      grid: {
        top:'35px',
        left: '3%',
        right: '6%',
        bottom: '4%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data:time,
        axisLabel: {
          showMaxLabel: true
        }
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '电导率(μS/CM)',
          type: 'line',
          large:true,
          smooth:true,
          data: phData,
          lineStyle:{
            width:5
          },
          itemStyle: {
            normal: {
              label: {
                show: true,
                position: 'top',
                textStyle: {
                  fontSize: 16,
                  color: "#fff"
                },
                formatter: (params) => {
                  if (phData.length - 1 == params.dataIndex) {
                    return params.value
                  } else {
                    return ""
                  }
                },
              },
            }
          },
        },

      ]
    };
    return option
  }
  render() {
    console.log('render')
    let template = '';
    const that = this;
    return (
      <div style={{ marginTop: '-24px' }} style={{ minHeight: '400px' }}>
        <Tabs defaultActiveKey="1">
          <TabPane tab="水质站点曲线" key="1">
            {/*{
              this.state.isWatch===-1?
              <div onClick={this.openWatch}  style={{marginBottom:'10px'}}><Button type={'primary'}>开启监控模式</Button> </div>
                :
                <Alert message="正处于监控模式" type="info" showIcon />
            }*/}
            <Row>
              <Col span={12}>
                <ReactEcharts
                  option={this.getOption()}
                  style={{ height: '285px', width: '100%' }}
                  theme='my_theme'
                />
              </Col>
              <Col span={12}> <ReactEcharts
                option={this.getOption2()}
                style={{ height: '285px', width: '100%' }}
                theme='my_theme'
              /></Col>
              <Col span={12}>
                <ReactEcharts
                  option={this.getOption3()}
                  style={{ height: '285px', width: '100%' }}
                  theme='my_theme'
                />
              </Col>
              <Col span={12}> <ReactEcharts
                option={this.getOption4()}
                style={{ height: '285px', width: '100%' }}
                theme='my_theme'
              /></Col>
            </Row>


          </TabPane>
          <TabPane tab="站点完整数据" key="3">
            <div style={{ marginLeft: '16px' }}>
              开始时间 : <DatePicker
              value={moment(this.state.start_date)}
              allowClear={false}
              format="YYYY-MM-DD"
              style={{ width: 150, marginRight: '10px' }}
              placeholder={'开始日期'}
              onChange={(e, dateString) => this.handleRangePickerChange(dateString, 'start_date')}
            />
              结束时间 : <DatePicker
              allowClear={false}
              value={moment(this.state.end_date)}
              format="YYYY-MM-DD"
              placeholder={'结束日期'}
              style={{ width: 150 }}
              onChange={(e, dateString) => this.handleRangePickerChange(dateString, 'end_date')}
            />
            <Button type={'primary'} style={{marginLeft:'10px'}} onClick={()=>{
                this.fetHistory()
              if(this.timer){
                clearInterval(this.timer)
              }
            }}>刷新</Button>
            </div>
            <Tabs size={'small'} style={{ marginTop: '8px' }}>
              {
                this.state.tabPanes.map((item, index) => {
                  let renderTab = '';
                  if (item.key === 'device') {
                    renderTab = <TabPane tab={item.name} key={item.key}>
                      <div>
                        <Table
                          style={{ color: '#fff' }}
                          className={`custom-small-table ${this.state[`device_0`].data.length === 0 && 'custom-small-table2'}`}
                          loading={this.state[`device_0`].loading}
                          rowKey={'id'}
                          dataSource={this.state.device_0.data}
                          columns={[
                            {
                              title: '采集时间',
                              dataIndex: 'collected_at',
                              width: 160,
                            },
                            {
                              title: '运行时间',
                              dataIndex: 'uptime',
                              width: 120,
                              render: (text, record) => (
                                timeStamp(record.data.uptime)
                              ),
                            },
                            {
                              title: '重置原因',
                              dataIndex: 'reset_reason',
                              width: 80,
                              render: (text, record) => (
                                record.data.reset_reason
                              ),
                            },
                            {
                              title: <span>供电电压(V)</span>,
                              dataIndex: 'supply_voltage',
                              width: 150,
                              render: (text, record) => (
                                (record.data.supply_voltage / 1000).toFixed(3)),
                            },
                            {
                              title: <span>信号质量(dbm)</span>,
                              dataIndex: 'network_signal_quality',
                              render: (text, record) => (
                                record.data.network_signal_quality
                              ),
                            },
                          ]}
                          pagination={false}
                          size="small"
                          scroll={{ x: true, y: 400 }}
                        />
                        <MyPagination className="history-pagination" searchCondition={{
                          type: item.key,
                          channel: 0,
                        }} meta={this.state[`${item.key}_0`].meta} handleSearch={this.fetch}/>
                      </div>
                    </TabPane>;
                  }
                  if (item.key === 'modbus') {
                    renderTab = <TabPane tab={item.name} key={item.key}>
                      <div>
                        <Table
                          style={{ color: '#fff' }}
                          className={`custom-small-table ${this.state[`modbus_0`].data.length === 0 && 'custom-small-table2'}`}
                          loading={this.state[`modbus_0`].loading}
                          rowKey={'id'}
                          dataSource={this.state.modbus_0.data}
                          columns={[
                            {
                              title: '采集时间',
                              dataIndex: 'collected_at',
                              width: 170
                            },
                            {
                              title: <span>PH值(pH)</span>,
                              width: 150,
                              dataIndex: 'ph',
                              render: (text, record) => {
                                if(this.state.config_data.modbus[0].channel1_type==1){
                                  return record.data.measure_value1+` (${record.data.temperature1}℃)`;
                                }else if(this.state.config_data.modbus[0].channel2_type==1){
                                  return record.data.measure_value2+` (${record.data.temperature2}℃)`;
                                }else if(this.state.config_data.modbus[0].channel3_type==1){
                                  return record.data.measure_value3+` (${record.data.temperature3}℃)`;
                                }else if(this.state.config_data.modbus[0].channel4_type==1){
                                  return record.data.measure_value4+` (${record.data.temperature4}℃)`;
                                }else{
                                  return  ""
                                }

                              },
                            },
                            {
                              title: <span>浊度(NTU)</span>,
                              width: 150,
                              dataIndex: 'instantaneous_flow',
                              render: (text, record) => {
                                if(this.state.config_data.modbus[0].channel1_type==2){
                                  return record.data.measure_value1+` (${record.data.temperature1}℃)`;
                                }else if(this.state.config_data.modbus[0].channel2_type==2){
                                  return record.data.measure_value2+` (${record.data.temperature2}℃)`;
                                }else if(this.state.config_data.modbus[0].channel3_type==2){
                                  return record.data.measure_value3+` (${record.data.temperature3}℃)`;
                                }else if(this.state.config_data.modbus[0].channel4_type==2){
                                  return record.data.measure_value4+` (${record.data.temperature4}℃)`;
                                }else{
                                  return  ""
                                }
                              },
                            },
                            {
                              title: <span>溶氧(ppm)</span>,
                              width: 150,
                              dataIndex: 'positive_cumulative_flow',
                              render: (text, record) => {
                                if(this.state.config_data.modbus[0].channel1_type==3){
                                  return record.data.measure_value1+` (${record.data.temperature1}℃)`;
                                }else if(this.state.config_data.modbus[0].channel2_type==3){
                                  return record.data.measure_value2+` (${record.data.temperature2}℃)`;
                                }else if(this.state.config_data.modbus[0].channel3_type==3){
                                  return record.data.measure_value3+` (${record.data.temperature3}℃)`;
                                }else if(this.state.config_data.modbus[0].channel4_type==3){
                                  return record.data.measure_value4+` (${record.data.temperature4}℃)`;
                                }else{
                                  return  ""
                                }
                              },
                            },
                            {
                              title: <span>电导率(μS/CM)</span>,
                              dataIndex: 'positive_running_time',
                              render: (text, record) => {
                                if(this.state.config_data.modbus[0].channel1_type==4){
                                  return record.data.measure_value1+` (${record.data.temperature1}℃)`;
                                }else if(this.state.config_data.modbus[0].channel2_type==4){
                                  return record.data.measure_value2+` (${record.data.temperature2}℃)`;
                                }else if(this.state.config_data.modbus[0].channel3_type==4){
                                  return record.data.measure_value3+` (${record.data.temperature3}℃)`;
                                }else if(this.state.config_data.modbus[0].channel4_type==4){
                                  return record.data.measure_value4+` (${record.data.temperature4}℃)`;
                                }else{
                                  return  ""
                                }
                              },
                            },

                          ]}
                          pagination={false}
                          size="small"
                          scroll={{ x: true, y: 405 }}
                        />
                        <MyPagination className="history-pagination" searchCondition={{
                          type: item.key,
                          channel: 0,
                        }} meta={this.state[`${item.key}_0`].meta} handleSearch={this.fetch}/>
                      </div>
                    </TabPane>;
                  }
                  return renderTab;
                })
              }
            </Tabs>

          </TabPane>
        </Tabs>


      </div>

    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);
